<!--
 * @Author: xxx
 * @Description:
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    width="30%"
    :title="title"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      :model="ruleForm"
      :rules="rules"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          :type="oldPwdinputState ? '' : 'password'"
          v-model="ruleForm.oldPassword"
        >
          <template #suffix>
            <div @click="oldPwdinputState = !oldPwdinputState">
              <el-icon v-if="oldPwdinputState"><View /></el-icon>
              <el-icon v-else><Hide /></el-icon>
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          :type="newPwdinputState ? '' : 'password'"
          v-model="ruleForm.newPassword"
        >
          <template #suffix>
            <div @click="newPwdinputState = !newPwdinputState">
              <el-icon v-if="newPwdinputState"><View /></el-icon>
              <el-icon v-else><Hide /></el-icon>
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input
          :type="secPwdinputState ? '' : 'password'"
          v-model="ruleForm.confirmPwd"
        >
          <template #suffix>
            <div @click="secPwdinputState = !secPwdinputState">
              <el-icon v-if="secPwdinputState"><View /></el-icon>
              <el-icon v-else><Hide /></el-icon>
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="">
        <span style="color: red"
          >说明：新密码最少6位，但不能超过15位！可以是任意组合但不能出现3个连续字符（123，abc）或三个相同字符（111，aaa）！</span
        >
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSure" :loading="isLoading"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import jsencrypt from 'jsencrypt'
import { ref, watch, toRefs } from 'vue'
import { updatePassword } from '@/api/com-api/common'
import { ElMessage } from 'element-plus'

let props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  // 1:新增  2：修改
  dialogType: {
    type: Number,
    default: 1,
  },
  // 一行数据
  tableRow: {
    type: Object,
    default() {
      return null
    },
  },
})

let emit = defineEmits(['update:dialogVisible', 'handleSuccess'])

let { dialogVisible, dialogType, tableRow } = toRefs(props)
let title = ref('')
let isLoading = ref(false)
let ruleFormRef = ref(null)
let roleList = ref([])

let oldPwdinputState = ref(false)
let newPwdinputState = ref(false)
let secPwdinputState = ref(false)

let validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入新密码！'))
  } else if (value === ruleForm.value.oldPassword) {
    callback(new Error('新密码不能和原密码一样！'))
  } else {
    let regex =
      /^[a-z]{6,15}$|[A-Z]{6,15}$|[a-zA-Z0-9\~\!\@\#\$\%\^\&\*\_\+\{\}\:\"\|\<\>\?\-\=\;\'\\\,\.\/]{6,15}$/
    if (regex.test(value) && value.length <= 15) {
      if (ruleForm.value.confirmPwd !== '') {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validateField('confirmPwd', () => null)
      }
      callback()
    } else {
      callback(new Error('密码长度只能是6-15位'))
    }
  }
}
let validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码！'))
  } else if (value !== ruleForm.value.newPassword) {
    callback(new Error('两次密码不一样!'))
  } else {
    callback()
  }
}

let ruleForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPwd: '',
})
let rules = ref({
  oldPassword: [
    {
      required: true,
      message: '请输入原密码！',
      trigger: 'blur',
    },
  ],
  newPassword: [
    {
      required: true,
      validator: validatePass,
      trigger: 'blur',
    },
  ],
  confirmPwd: [
    {
      required: true,
      validator: validatePass2,
      trigger: 'blur',
    },
  ],
})

let handleClose = () => {
  ruleFormRef.value.resetFields()
  emit('update:dialogVisible', false)
}
let handleSure = async () => {
  let valid = await ruleFormRef.value.validate()
  if (valid) {
    let { oldPassword, newPassword, confirmPwd } = ruleForm.value
    let params = {
      oldPassword: getRsaPassword(oldPassword),
      newPassword: getRsaPassword(newPassword),
      confirmPwd: getRsaPassword(confirmPwd),
    }
    isLoading.value = true
    updatePassword(params).then((res) => {
      isLoading.value = false
      if (res.code === 200) {
        ElMessage.success('操作成功')
        emit('handleSuccess')
        handleClose()
      }
    })
  }
}

// 密码加密
let getRsaPassword = (pas) => {
  let jse = new jsencrypt()
  jse.setPublicKey(`-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKdKk67IWN0Qd94HuSlqbx4cqMY
lq31Cyp4BUe2ByqkZlymuWlFsr4byVcPArPcz2ReJGUVaV3dLOH5A8c/od
msCAwEAAQ==
-----END PUBLIC KEY-----`)
  return jse.encrypt(pas)
}

watch(dialogVisible, (val) => {
  if (val) {
    switch (dialogType.value) {
      // 修改密码
      case 1:
        title.value = '修改密码'
        ruleForm.value = {
          oldPassword: '',
          newPassword: '',
          confirmPwd: '',
        }
        break
      //编辑
      case 2:
        title.value = '编辑用户'
        ruleForm.value = { ...tableRow.value }
        break
    }
  }
})
</script>
<style></style>
